package com.fengye.middleware.redis.demo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengye.middleware.redis.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**
 * @author sky
 * @date 2021/06/07 21:37
 */
@Component
@Slf4j
public class StringRedisTemplateDemo {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 采用RedisTemplate将字符串信息写入缓存中，并读取出来展示在控制台上
     */
    public void writeAndRead() {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String KEY = "REDIS:DEMO1:KEY";
        String VALUE = "REDIS:DEMO1:VALUE";
        operations.set(KEY, VALUE);
        log.info("写入redis: key={},value={}", KEY, VALUE);
        Object obj = operations.get(KEY);
        log.info("读取redis：key={},value={}", KEY, obj);
    }

    /**
     * 采用RedisTemplate将对象信息序列化为JSON格式的字符串后写入缓存中，
     * 然后将其读取出来，最后反序列化解析其中的内容并展示在控制台上
     */
    public void writeAndReadForObject() throws JsonProcessingException {
        User user = new User(1, "error", "错误信息");
        String key = "REDIS:OBJECT:KEY";
        String value = objectMapper.writeValueAsString(user);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(key, value);
        log.info("写入缓存,key={},value={}", key, value);
        Object obj = operations.get(key);
        if (obj != null) {
            User saved = objectMapper.readValue(obj.toString(), User.class);
            log.info("读取redis,key={},value={}", key, saved);
        }
    }

}
